package com.jyh.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author JYH
 * @version 1.0
 * @date 2022/11/23 16:29
 */
public class JWTUtil {
    private static final String SIGN="aaa";
    //1.通过jwt生成token字符串；
    public static String createToken(Map<String,Object> param){

        Map<String,Object> head = new HashMap<>();
        head.put("alg","HS256");
        head.put("typ","JWT");
        //定义办法时间
        Date iss = new Date();
        //过期时间
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,30);
        Date expire = nowTime.getTime();

        String token= JWT.create()
                //指定头信息
                .withHeader(head)
                //载荷的过期时间
                .withExpiresAt(expire)
                //颁发时间
                .withIssuedAt(iss)
                //颁发人
                .withIssuer("jyh")
                //自定义的载荷内容
                .withClaim("userInfo",param)
                //签名
                .sign(Algorithm.HMAC256(SIGN));

        return token;
    }


    //2.判断token是否合法
    public static boolean verifyToken(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SIGN)).build();

        try {
            DecodedJWT verify = build.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //3.解析token的内容
    public static Map<String,Object> decodeJWT(String token){
        Map<String, Object> userInfo = JWT.decode(token).getClaim("userInfo").asMap();
        return userInfo;
    }

    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","蒋艳航");
        map.put("id",1);
        map.put("age",22);
        String token = createToken(map);
        System.out.println(token);

        Map<String, Object> map2
                = decodeJWT(token);
        System.out.println(map2);

        boolean b = verifyToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6eyJuYW1lIjoi6JKL6Imz6IiqIiwiaWQiOjEsImFnZSI6MjJ9LCJpc3MiOiJqeWgiLCJleHAiOjE2NjkxOTU4MzcsImlhdCI6MTY2OTE5NDAzN30.wVXxVCRVqIn8v0ccC9_HY1zC6IyJqPqHUXH-gafSOwc");
        System.out.println(b);
    }
}
